package com.flea.service;

import com.flea.exception.ServiceException;
import com.flea.model.UploadFile;
import com.flea.repository.jdbc.UploadFileRepository;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.UUID;

@Service
public class UploadFileService {

    private static final String SAVE_PATH = "d:/fleafile/";

    @Resource
    private UploadFileRepository uploadFileRepository;

    public Integer save(MultipartFile multipartFile) throws IOException {
        // 重命名  head.jpg -> 4d6d0026-f96b-4a26-a73d-5c1647aa5cb6.jpg
        String originalFilename = multipartFile.getOriginalFilename();
        String newFilename = UUID.randomUUID() + originalFilename.substring(originalFilename.indexOf("."));
        // 存硬盘
        multipartFile.transferTo(Paths.get(SAVE_PATH, newFilename));

        //存数据库
        UploadFile uploadFile = new UploadFile();
        uploadFile.setName(newFilename);
        uploadFile.setContentType(multipartFile.getContentType());
        uploadFile.setCreateTime(Instant.now());
        uploadFile.setUpdateTime(Instant.now());

        uploadFile = uploadFileRepository.save(uploadFile);

        return uploadFile.getId();
    }

    public static void main(String[] args) {
        System.out.println(UUID.randomUUID());
        System.out.println(UUID.randomUUID());
        System.out.println(UUID.randomUUID());
    }

    public UploadFile findUploadFile(Integer id) {
        return uploadFileRepository.findById(id).orElseThrow(() -> new ServiceException("文件不存在"));
    }

    public File findLocalFile(UploadFile uploadFile) {
        return new File(SAVE_PATH + uploadFile.getName());
    }

    public File findLocalFile(Integer id) {
        UploadFile uploadFile = findUploadFile(id);
        File file = new File(SAVE_PATH + uploadFile.getName());
        return file;
    }

}
